<template>
  <div style="width: 100%; height: 100%; display: flex; flex-direction: column; padding: 1rem">
    <div style="margin-bottom: 1rem"><el-button type="primary" @click="uploadDialog.flag = true">{{ translate('上传资源') }}</el-button></div>
    <div ref="containerRef" style="flex: 1; display: flex; flex-wrap: wrap; overflow: auto; align-content: flex-start">
      <template v-for="item in list" :key="item">
        <el-card class="res-card" :style="`width: calc(${w} - 1rem)`" shadow="hover">
          <template #header>
            <div style="width: 100%; display: flex; align-items: center">
              <div class="file-name" :title="item.name">{{ item.name }}</div>
              <el-button-group>
                <el-button size="small" icon="DocumentCopy" @click="handleCopy('http://127.0.0.1:18221/res?id=' + item.id)"/>
                <el-button size="small" type="danger" icon="Close" @click="handleDelete(item)"/>
              </el-button-group>
            </div>
          </template>
          <el-image style="width: 100px; height: 100px; margin-bottom: .4rem" :src="`http://127.0.0.1:18221/res?id=${item.id}`"
                    :zoom-rate="1.2" :preview-src-list="[`http://127.0.0.1:18221/res?id=${item.id}`]" hide-on-click-modal fit="contain"/>
        </el-card>
      </template>
      <el-card :style="`width: calc(${w} - 1rem);cursor: no-drop; color: var(--z-note-color); background: var(--z-light-color)`"
               class="res-card" shadow="never">
        {{ translate('没有更多了') }}
      </el-card>
    </div>

    <el-dialog v-model="uploadDialog.flag" :title="translate('新建资源')" width="480px" draggable @close="uploadDialog = {}">
      <el-form v-loading="loadingFlag" label-position="left" label-width="100px">
        <el-form-item :label="translate('自定义ID')">
          <el-input v-model="uploadDialog.id" :placeholder="translate('不填写则使用文件MD5校验值')"/>
        </el-form-item>
        <el-form-item :label="translate('资源文件')">
          <el-upload style="width: 100%" drag action="#" :show-file-list="false" :auto-upload="false" @change="handleChange">
            <el-icon v-if="!uploadDialog.file" class="el-icon--upload"><component is="UploadFilled"/></el-icon>
            <div v-if="!uploadDialog.file" class="el-upload__text">
              <em>{{ translate('点击选择或拖拽至此') }}</em>
            </div>
            <el-image v-else style="width: 120px; height: 120px" :src="windowURL.createObjectURL(uploadDialog.file)"/>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :loading="loadingFlag" @click="uploadDialog = {}">{{ translate('关闭') }}</el-button>
        <el-button :loading="loadingFlag" type="primary" @click="handleSubmit">{{ translate('提交') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {inject, onMounted, ref} from 'vue'
import {useResizeObserver} from '@vueuse/core'
import {ElMessage, ElMessageBox} from 'element-plus'

const layout = inject('layout')
const translate = inject('translate')
const w = ref('0px')
const list = ref([])
const containerRef = ref()
const uploadDialog = ref({})
const loadingFlag = ref(false)
const windowURL = window.URL || window.webkitURL

function handleCopy(text) {
  const input = document.createElement('input') // 创建input对象
  input.value = text // 设置复制内容
  document.body.appendChild(input) // 添加临时实例
  input.select() // 选择实例内容
  document.execCommand('Copy') // 执行复制
  document.body.removeChild(input) // 删除临时实例
  ElMessage.success(translate('复制成功'))
}

function handlePullData() {
  layout.value.mainLoading = true
  return request({
    url: '/res/list',
    method: 'GET',
  }).then(res => {
    list.value = res.data.data
  }).finally(() => layout.value.mainLoading = false)
}

function handleChange(uploadFile) {
  if (!uploadFile.raw.type || !'image/png,image/jpg,image/jpeg,image/gif'.includes(uploadFile.raw.type))
    return ElMessage.error(translate('仅支持PNG，JPG，GIF图片类型'))
  uploadDialog.value.file = uploadFile.raw
}

function handleSubmit() {
  loadingFlag.value = true
  let data = {
    id: uploadDialog.value['id'],
    file: uploadDialog.value['file'],
  }
  if (!data.id) delete data.id
  request.upload({
    url: '/res',
    method: 'POST',
    data: data
  }).then(() => {
    ElMessage.success('操作成功')
    uploadDialog.value = {}
    handlePullData()
  }).finally(() => loadingFlag.value = false)
}

function handleDelete(item) {
  ElMessageBox.confirm(translate('确认提交'))
      .then(() => {
        layout.value.mainLoading = true
        return request({
          url: 'res',
          method: 'DELETE',
          data: [item['id']]
        }).then(() => {
          ElMessage.success('操作成功')
          list.value = list.value.filter(o => o['id'] !== item.id)
        })
      }).catch(() => {}).finally(() => layout.value.mainLoading = false)
}

handlePullData()
onMounted(() => {
  let __resizeTimeoutId = null // 防抖
  useResizeObserver(containerRef, ([entry]) => {
    clearTimeout(__resizeTimeoutId)
    __resizeTimeoutId = setTimeout(() => {
      const {width} = entry.contentRect
      const size = Math.floor(width / 200)
      w.value = width / size + 'px'
    }, 100)
  })
})
</script>

<style lang="scss">
.res-card {
  height: 160px;
  margin: 0 1rem 1rem 0;
  display: flex;
  flex-direction: column;

  .el-card__header {
    margin: 0;
    padding: .4rem .8rem;

    .file-name {
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      padding-right: .4rem;
      font-size: 12px;
    }
  }

  .el-card__body {
    flex: 1;
    margin: 0;
    padding: .4rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
</style>